﻿Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Imports System.Threading.Tasks

Module SettingUtil
    Public ReadOnly AppPath As String = Application.StartupPath

    Public ReadOnly SettingFile As String = My.Settings.SettingFile
    Dim Serializer As New Xml.Serialization.XmlSerializer(GetType(Settings))

    Public Function ReadSetting(ByVal str As String) As Settings
        Dim s As Settings = Nothing
        If String.IsNullOrEmpty(str) Then Return Settings.Default
        Try
            Using reader = New MemoryStream(Encoding.UTF8.GetBytes(str))
                s = Serializer.Deserialize(reader)
                reader.Close()
            End Using
        Catch ex As Exception
            s = Settings.Default
        End Try
        Return If(s, Settings.Default)
    End Function

    Public Function GetSettingString(ByVal setting As Settings) As String
        Dim r As String
        Try
            Using stream = New MemoryStream(200)
                Serializer.Serialize(stream, setting)
                Using reader = New StreamReader(stream, Encoding.UTF8)
                    stream.Seek(0, SeekOrigin.Begin)
                    r = reader.ReadToEnd
                End Using
                stream.Close()
            End Using
            Return r
        Catch ex As Exception
            Return String.Empty
        End Try
    End Function
End Module
